const heorsmodle = require('../module/modleHeors');
const moment = require('moment');
class HeorsService {
  async getHeors(req, res) {
    let result = await heorsmodle.findAll();
    res.json({ status: 200, message: result })
  }

  async getHeorsByID(req, res) {
    const id = req.params.id;
    let result = await heorsmodle.findById(id);
    res.json({ status: 200, message: result.length === 0 ? '该英雄未找到或被删除' : result });
  }

  async upDataHeors(req, res) {
    const id = req.params.id;
    const body = req.body;
    body.add_time = moment().format('YYYY-MM-DD HH:mm:ss');
    let result = await heorsmodle.upDate(body, id);
    let isChange = result.affectedRows >= 1;
    res.json({
      status: isChange ? 200 : -200,
      message: isChange ? '修改成功' : '修改失败'
    })
  }

  async addHeors(req, res) {
    try {
      let body = req.body;
      body.add_time = moment().format('YYYY-MM-DD HH:mm:ss');
      let nameresult = await heorsmodle.findStatus(body.name);
      let isName = nameresult.length >= 1;
      if (isName) {
        await heorsmodle.upStatus(body.add_time, body.name);
        res.json({ status: 200, message: '添加成功' });
      } else {
        let result = await heorsmodle.creat(body);
        let isChange = result.affectedRows >= 1;
        res.json({
          status: isChange ? 200 : -200,
          message: isChange ? '添加成功' : '添加失败'
        })
      }
    } catch (error) {
      res.json({ status: -200, message: '该英雄已存在无需重复添加' });
    }
  }

  async deleteHeors(req, res) {
    const id = req.params.id;
    let result = await heorsmodle.delete(id);
    let isChange = result.affectedRows >= 1;
    res.json({
      status: isChange ? 200 : -200,
      message: isChange ? '删除成功' : '删除失败'
    })
  }
}
module.exports = new HeorsService();